import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import 'package:permission_handler/permission_handler.dart';
import 'dart:io' show Platform;

class speech extends StatefulWidget {
  const speech({super.key});

  @override
  State<speech> createState() => _speechState();
}

class _speechState extends State<speech> {
  final stt.SpeechToText _speech = stt.SpeechToText();
  bool _isListening = false;
  String _recognizedText = "未开始识别";
  bool _speechAvailable = false;
  String? _activeLocaleId; // 当前使用的语言ID
  List<stt.LocaleName> _supportedLocales = []; // 支持的语言列表

  // 权限状态跟踪
  bool _micPermissionGranted = false;
  bool _speechPermissionGranted = false;

  @override
  void initState() {
    super.initState();
    // 初始化时先检查所有必要权限
    _checkAllPermissions();
  }

  // 检查所有必要权限（麦克风 + 语音识别）
  Future<void> _checkAllPermissions() async {
    // 检查麦克风权限（必须）
    await _checkMicrophonePermission();

    // 检查语音识别权限（根据平台处理）
    await _checkSpeechRecognitionPermission();

    // 所有权限都通过后初始化语音识别
    if (_micPermissionGranted && _speechPermissionGranted) {
      await _initSpeechRecognizer();
    } else {
      setState(() {
        _recognizedText = "请授予所有必要权限以使用语音识别";
      });
    }
  }

  // 检查麦克风权限
  Future<void> _checkMicrophonePermission() async {
    PermissionStatus status = await Permission.microphone.status;

    // 状态变化时更新UI
    _updatePermissionStatus(isMic: true, isGranted: status.isGranted);

    // 未授予时请求权限
    if (!status.isGranted) {
      status = await Permission.microphone.request();
      _updatePermissionStatus(isMic: true, isGranted: status.isGranted);

      // 永久拒绝时引导到设置
      if (status.isPermanentlyDenied) {
        _showPermissionSettingsDialog("麦克风");
      }
    }
  }

  // 检查语音识别权限（iOS需要单独处理）
  Future<void> _checkSpeechRecognitionPermission() async {
    // Android 平台：语音识别权限通常包含在麦克风权限中
    // iOS 平台：需要单独的语音识别权限
    if (Platform.isIOS) {
      PermissionStatus status = await Permission.speech.status;

      _updatePermissionStatus(isMic: false, isGranted: status.isGranted);

      if (!status.isGranted) {
        status = await Permission.speech.request();
        _updatePermissionStatus(isMic: false, isGranted: status.isGranted);

        if (status.isPermanentlyDenied) {
          _showPermissionSettingsDialog("语音识别");
        }
      }
    } else {
      // Android 默认为已授予（依赖麦克风权限）
      _updatePermissionStatus(isMic: false, isGranted: true);
    }
  }

  // 更新权限状态（统一处理UI刷新）
  void _updatePermissionStatus({required bool isMic, required bool isGranted}) {
    setState(() {
      if (isMic) {
        _micPermissionGranted = isGranted;
      } else {
        _speechPermissionGranted = isGranted;
      }
    });
  }

  // 显示权限设置对话框
  void _showPermissionSettingsDialog(String permissionName) {
    showDialog(
      context: context,
      barrierDismissible: false, // 必须处理才能关闭
      builder: (context) => AlertDialog(
        title: Text("需要$permissionName权限"),
        content: Text("请在设置中开启$permissionName权限以使用语音识别功能"),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // 跳转到应用设置页面
              openAppSettings();
            },
            child: const Text("去设置"),
          ),
        ],
      ),
    );
  }

  // 初始化语音识别器
  Future<void> _initSpeechRecognizer() async {
    // 确保权限已授予
    if (!_micPermissionGranted || !_speechPermissionGranted) {
      return;
    }

    // 初始化语音识别
    bool available = await _speech.initialize(
      onStatus: (status) {
        debugPrint("语音识别状态更新：$status");
        // 识别完成时自动停止监听
        if (status == "done") {
          setState(() => _isListening = false);
        }
      },
      onError: (error) {
        debugPrint("语音识别错误：${error.errorMsg}（${error}）");
        setState(() {
          _recognizedText = "识别错误：${error.errorMsg}";
          _isListening = false;
        });
      },
    );

    if (available) {
      setState(() => _speechAvailable = true);
      // 获取支持的语言列表
      _supportedLocales = await _speech.locales();
      debugPrint("支持的语言：${_supportedLocales.map((l) => l.localeId).toList()}");

      // 默认选择中文（如果支持）
      _activeLocaleId = _supportedLocales
          .firstWhere(
            (locale) => locale.localeId.startsWith('zh'),
            orElse: () => _supportedLocales.first,
          )
          .localeId;
    } else {
      setState(() {
        _recognizedText = "当前设备不支持语音识别";
      });
    }
  }

  // 开始语音识别
  void _startListening() async {
    // 检查前置条件
    if (!_canStartListening()) return;

    // 开始监听
    await _speech.listen(
      onResult: (result) {
        setState(() {
          _recognizedText = result.recognizedWords;
        });
        debugPrint("识别结果：${result}（最终：${result}）");
      },
      localeId: _activeLocaleId,
      partialResults: true, // 实时返回中间结果
      listenFor: const Duration(seconds: 60), // 最长识别时间
      pauseFor: const Duration(seconds: 3), // 停顿超时时间
    );

    setState(() => _isListening = true);
  }

  // 停止语音识别
  void _stopListening() async {
    if (_isListening) {
      await _speech.stop();
      setState(() => _isListening = false);
    }
  }

  // 检查是否可以开始识别
  bool _canStartListening() {
    if (!_speechAvailable) {
      _showErrorDialog("语音识别未初始化", "请检查权限或设备是否支持");
      return false;
    }

    if (_isListening) {
      return false;
    }

    if (!_micPermissionGranted || !_speechPermissionGranted) {
      _showErrorDialog("权限不足", "请先授予所有必要权限");
      _checkAllPermissions(); // 重新检查权限
      return false;
    }

    return true;
  }

  // 显示错误对话框
  void _showErrorDialog(String title, String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text("确定"),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("语音转文字（权限增强版）"),
        actions: [
          // 显示权限状态
          IconButton(
            icon: const Icon(Icons.info),
            onPressed: () => _showPermissionStatusDialog(),
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 识别结果显示区域
            Expanded(
              child: Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey[300]!),
                ),
                child: SingleChildScrollView(
                  child: Text(
                    _recognizedText,
                    style: const TextStyle(fontSize: 18, color: Colors.black87),
                  ),
                ),
              ),
            ),
            const SizedBox(height: 20),
            // 语言选择下拉框（如果有多种语言支持）
            if (_supportedLocales.length > 1)
              DropdownButton<String>(
                value: _activeLocaleId,
                items: _supportedLocales
                    .map((locale) => DropdownMenuItem(
                          value: locale.localeId,
                          child: Text("${locale.name} (${locale.localeId})"),
                        ))
                    .toList(),
                onChanged: (value) {
                  if (value != null) {
                    setState(() => _activeLocaleId = value);
                  }
                },
                hint: const Text("选择识别语言"),
              ),
            const SizedBox(height: 20),
            // 控制按钮
            FloatingActionButton.large(
              onPressed: _isListening ? _stopListening : _startListening,
              backgroundColor: _isListening ? Colors.red : Colors.blue,
              child: Icon(
                _isListening ? Icons.stop : Icons.mic,
                size: 32,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 显示权限状态对话框
  void _showPermissionStatusDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("权限状态"),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildPermissionStatusItem(
              "麦克风权限",
              _micPermissionGranted ? "已授予" : "未授予",
              _micPermissionGranted,
            ),
            _buildPermissionStatusItem(
              "语音识别权限",
              _speechPermissionGranted ? "已授予" : "未授予",
              _speechPermissionGranted,
            ),
            _buildPermissionStatusItem(
              "语音引擎可用",
              _speechAvailable ? "可用" : "不可用",
              _speechAvailable,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text("关闭"),
          ),
        ],
      ),
    );
  }

  // 构建权限状态项
  Widget _buildPermissionStatusItem(
      String label, String status, bool isGranted) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label),
          Text(
            status,
            style: TextStyle(
              color: isGranted ? Colors.green : Colors.red,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    // 停止识别并释放资源
    _speech.stop();
    super.dispose();
  }
}
